<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui">
    <title>好味道</title>
    <link rel="icon" href="./../images/favicon.ico">
    <!--element-ui的样式-->
    <link rel="stylesheet" href="../../backend/plugins/element-ui/index.css" />
    <!-- 引入样式  -->
    <link rel="stylesheet" href="../styles/index.css" />
    <!--引入vant样式-->
    <link rel="stylesheet" href="../styles/vant.min.css"/>
    <!--本页面内容的样式-->
    <link rel="stylesheet" href="./../styles/user.css" />
</head>
<body>
    <div id="user" class="app">
        <el-dialog
                title="修改资料"
                :visible.sync="dialogVisible"
                width="100%"
        >
            <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="85px">

                <el-form-item label="姓名" prop="name">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>

                <el-form-item label="手机号">
                    <el-input readonly="readonly" v-model="ruleForm.phone"></el-input>
                </el-form-item>

                <el-form-item label="身份证号" prop="idNumber">
                    <el-input v-model="ruleForm.idNumber"></el-input>
                </el-form-item>

                <el-form-item>
                    性别
                    <el-radio v-model="ruleForm.sex" label="1">男</el-radio>
                    <el-radio v-model="ruleForm.sex" label="2">女</el-radio>
                </el-form-item>

                <el-form-item label="上传图片：">
                <el-upload
                        class="avatar-uploader"
                        action="/common/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="onChange"
                        ref="upload"
                >
                    <img
                            v-if="imageUrl"
                            :src="imageUrl"
                            alt=""
                            class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click.native="textEditDefine('ruleForm')">提交</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>


            </el-form>

        </el-dialog>



        <div class="divHead">
            <div class="divTitle">
                <i class="el-icon-arrow-left" @click="goBack"></i>个人中心
            </div>
            <div class="divUser" @click="userbtn">
                <img :src="brand.imageUrl"/>
                <div class="desc">
                    <div class="divName">{{brand.name}} <img :src=" brand.sex === '1' ? './../images/men.png' : './../images/women.png'"/></div>
                    <div class="divPhone">{{userPhone}}</div>
                </div>
            </div>
        </div>

        <div class="divContent">
            <div class="divLinks">
                <div class="item" @click="toAddressPage">
                    <img src="./../images/locations.png"/>
                    <span>地址管理</span>
                    <i class="el-icon-arrow-right"></i>
                </div>
                <div class="divSplit"></div>
                <div class="item" @click="toOrderPage">
                    <img src="./../images/orders.png"/>
                    <span>历史订单</span>
                    <i class="el-icon-arrow-right"></i>
                </div>
            </div>
            <div class="divOrders" v-if="order[0]">
                <div class="title">最新订单</div>
                <div class="timeStatus">
                    <span>{{order[0].orderTime}}</span>
                    <span>{{getStatus(order[0].status)}}</span>
                    <!-- <span>正在派送</span> -->
                </div>
                <div class="dishList">
                    <div v-for="(item,index) in order[0].orderDetails" :key="index" class="item">
                        <span>{{item.name}}</span>
                        <span>x{{item.number}}</span>
                    </div>
                </div>
                <div class="result">
                    <span>共{{order[0].sumNum}} 件商品,实付</span>
                    <span class="price">￥{{order[0].amount}}</span>
                </div>
                <div class="btn" v-if="order[0].status === 4">
                    <div class="btnAgain" @click="addOrderAgain">再来一单</div>
                </div>
                <div class="btn" v-if="order[0].status === 2">
                    <div class="btnAgain" @click="cancelOrder">取消订单</div>
                </div>
            </div>
            <div class="quitLogin" @click="toPageLogin">
                退出登录
            </div>
        </div>
    </div>



    <!-- 开发环境版本，包含了有帮助的命令行警告 -->

    <script src="../../backend/plugins/vue/vue.js"></script>
    <!-- 引入组件库 -->

    <script src="../../backend/plugins/element-ui/index.js"></script>

    <!-- 引入vant组件 -->
    <script src="./../js/vant.min.js"></script>    
    <!--不同屏幕尺寸根字体设置-->
    <script src="./../js/base.js"></script>
    <!-- 引入axios -->
    <script src="../../backend/plugins/axios/axios.min.js"></script>
    <script src="./../js/request.js"></script>
    <script src="./../api/order.js"></script>
    <script src="./../api/login.js"></script>
    <script>
        new Vue({
            el:"#user",
            data(){
                return {

                    imageUrl: '',

                    // 表单展示数据
                    ruleForm: {
                        id:'',
                        name:'',
                        sex: '1',
                        phone:'',
                        idNumber:'',
                        avatar: '',
                    },

                    rules: {
                        name: [
                            { required: true, message: '请输名字', trigger: 'blur' },
                            { min: 1, max:6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
                        ],
                        idNumber: [
                            { required: true, message: '请输身份证号', trigger: 'blur' },
                            { min: 18, max:18, message: '请输入规范的身份证号', trigger: 'blur' }
                        ],
                    },
                    // 展示主页面数据
                    brand:{
                        id:'',
                        name:'',
                        sex: '1',
                        phone:'',
                        idNumber:'',
                        avatar: '',
                        imageUrl: '',
                    },

                    dialogVisible: false,

                    form:{
                        phone:'',
                        code:''
                    },
                    msgFlag:false,
                    order:[{
                        orderTime:'',//下单时间
                        status:undefined,//订单状态 1已结账，2未结账，3已退单，4已完成，5已取消
                        orderDetails:[{
                            name:'',//菜品名称
                            number:undefined,//数量
                        }],//明细
                        amount:undefined,//实收金额
                        sumNum:0,//菜品总数
                    }],
                }
            },
            computed:{},
            created(){
                this.userPhone =sessionStorage.getItem("userPhone")
                this.initData()
            },
            mounted(){


            },
            methods:{
                // 获取用户资料
                async getUser(){
                    const res = await updateUserApi()
                    this.ruleForm=res.data
                    Object.assign(this.brand, this.ruleForm)
                    if(this.brand.avatar != null) {
                        this.brand.imageUrl = `/common/download?name=${this.brand.avatar}`;
                        this.imageUrl = `/common/download?name=${this.brand.avatar}`;
                    }
                },
                // 修改用户资料，反显
                userbtn(){
                    this.dialogVisible = true
                    this.getUser()
                },

                //点击提交按钮发送用户表单数据
                initdate(){
                    var _this = this;
                    Object.assign(this.brand, this.ruleForm)
                    const res =updateSubmitApi(this.brand);
                    res.then((data)=>{
                        // 发送ajax请求，添加数据
                        if(data.code == "1"){
                            //添加成功
                            this.brand.imageUrl = `/common/download?name=${this.brand.avatar}`;
                            //关闭窗口
                            _this.dialogVisible = false;
                            // 弹出消息提示
                            _this.$message({
                                message: '修改成功！',
                                type: 'success'
                            });
                        }
                        return false;
                    })
                },

                // 提交用户资料--提交按钮
                async textEditDefine(formName){

                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            console.log("chenggong")
                            // alert('submit!');
                            this.initdate()

                        } else {
                            console.log('error submit!!');
                            return false;
                        }
                    });


                },

                handleAvatarSuccess (response, file, fileList) {

                    // 拼接down接口预览
                    if(response.code === 0 && response.msg === '未登录'){
                        window.top.location.href = '/backend/page/login/login.html'
                    }else{
                        console.log(response)
                        this.imageUrl = `/common/download?name=${response.data}`
                        this.ruleForm.avatar = response.data;
                    }
                },

                onChange (file) {
                    if(file){
                        const suffix = file.name.split('.')[1]
                        const size = file.size / 1024 / 1024 < 2
                        if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                            this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
                            this.$refs.upload.clearFiles()
                            return false
                        }
                        if(!size){
                            this.$message.error('上传文件大小不能超过 2MB!')
                            return false
                        }
                        return file
                    }
                },


                goBack(){
                    history.go(-1)
                },
                toAddressPage(){
                    window.requestAnimationFrame(()=>{
                        window.location.href = '/front/page/address.html'
                    })  
                },
                toOrderPage(){
                    window.requestAnimationFrame(()=>{
                        window.location.href = '/front/page/order.html'
                    }) 
                },
                initData(){
                    this.getLatestOrder()
                    this.getUser()
                },
                async getLatestOrder(){
                    const params = {
                        page:1,
                        pageSize:1
                    }
                    const res = await orderPagingApi(params)
                    if(res.code === 1){
                        this.order = res.data.records
                        if(this.order && this.order[0].orderDetails){
                            let number = 0
                            this.order[0].orderDetails.forEach(item=>{
                                number += item.number
                            })
                            this.order[0].sumNum = number
                        }
                    }else{
                        this.$notify({ type:'warning', message:res.msg});
                    }
                },
                getStatus(status){
                    let str = ''
                    switch(status){
                        case 1:
                            str =  '待付款'
                        break;
                        case 2:
                            str =  '正在派送'
                        break;
                        case 3:
                            str =  '已派送'
                        break;
                        case 4:
                            str =  '已完成'
                        break;
                        case 5:
                            str =  '已取消'
                        break;

                    }
                    return str
                },
                async addOrderAgain(){
                    const res = await orderAgainApi({id:this.order[0].id})
                    if(res.code === 1){
                        window.requestAnimationFrame(()=>{
                            window.location.href = '/front/index.html'
                        }) 
                    }else{
                        this.$notify({ type:'warning', message:res.msg});
                    }
                },
                cancelOrder(){
                    this.$dialog.confirm({
                        title: '确认取消',
                        message: '确认要取消当前订单吗？',
                    })
                        .then(async () => {
                            const res = await orderCancelApi({id:this.order[0].id})
                            if(res.code === 1){
                                window.requestAnimationFrame(()=>{
                                    window.location.reload()
                                })
                            }else{
                                this.$notify({ type:'warning', message:res.msg});
                            }
                        })
                        .catch(() => {
                        });
                },
                async toPageLogin(){
                    const res = await loginoutApi()
                    if(res.code === 1){
                        window.requestAnimationFrame(()=>{
                            window.location.href = '/front/page/login.html'
                        }) 
                    }else{
                        this.$notify({ type:'warning', message:res.msg});
                    }                
                }
            }
        })
    </script>
</body>
</html>